<template>
  <div class="wechat">
    <!-- 卡片视图区域 -->
    <div class="wechat_card">
      <!--搜索框与按钮-->
      <el-row :gutter="20"
              class="wechat_card_head"
              type="flex">
        <el-col :span="6">

          <el-input placeholder="输入类型名称查询"
                    size="medium"
                    v-model="queryInfo.query"
                    clearable
                    @clear="getTableList">
            <el-button slot="append"
                       size="medium"
                       icon="el-icon-search"
                       @click="getTableList"></el-button>
          </el-input>
        </el-col>

        <el-button v-has="'6221'"
                   size="medium"
                   class="btn_head_medium"
                   type="primary"
                   @click="addType"
                   icon="el-icon-circle-plus-outline">新增类型</el-button>

        <!-- 表格列筛选和导出 -->
        <div class="tools_head">
          <el-tooltip content="导出excel"
                      placement="bottom">
            <el-button size="small"
                       icon="el-icon-download"
                       style="margin-left: 10px"
                       @click="exportDataToExcel"></el-button>
          </el-tooltip>
        </div>

      </el-row>

      <!-- 表格区域 -->
      <el-table :data="tableFilterData.dataList"
                height="85%"
                border
                stripe
                size="small"
                :header-cell-style="{ textAlign: 'center' }"
                :cell-style="{ textAlign: 'center' }"
                @selection-change="handleSelectionChange"
                style="width: 100%"
                row-key="id"
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <el-table-column prop="name"
                         label="设备类型"
                         width="">
        </el-table-column>
        <el-table-column prop="memo"
                         label="备注"
                         width="">
        </el-table-column>
        <el-table-column label="操作"
                         width="">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button v-has="'6222'"
                       type="primary"
                       icon="el-icon-edit"
                       size="mini"
                       @click="showEditDialog(scope.row)"></el-button>
            <!-- 删除按钮 -->
            <el-button v-has="'6223'"
                       type="danger"
                       icon="el-icon-delete"
                       size="mini"
                       @click="deleteRecordById(scope.row)"></el-button>

          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="this.queryInfo.pagenum"
                     :page-sizes="[3, 7, 15, 20, 30]"
                     :page-size="this.queryInfo.pagesize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total"></el-pagination>

      <!-- 添加类型的对话框 -->
      <el-dialog title="添加设备类型"
                 :visible.sync="addDialogVisible"
                 @close="addDialogClosed"
                 width="30%">
        <!-- 内容主体区 -->
        <el-form :model="addForm"
                 :rules="addFormRules"
                 ref="addFormRef"
                 label-width="70px">
          <el-form-item label="分类名称"
                        prop="name">
            <el-input v-model="addForm.name"></el-input>
          </el-form-item>

          <el-form-item label="父级分类"
                        prop="parentId">
            <el-select v-model="addForm.parentId"
                       placeholder="请选择">
              <el-option v-for="item in this.nameList"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="备注"
                        prop="memo">
            <el-input type="textarea"
                      v-model="addForm.memo"></el-input>
          </el-form-item>

        </el-form>
        <!-- 底部区域 -->
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="addRecord">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改记录对话框 -->
      <el-dialog title="修改记录"
                 :visible.sync="editDialogVisible"
                 width="50%"
                 @close="editDialogClosed">
        <el-form :model="editForm"
                 :rules="editFormRules"
                 ref="editFormRef"
                 label-width="70px">
          <el-form-item label="类型名称">
            <el-input v-model="editForm.name"></el-input>
          </el-form-item>
          <el-form-item v-if="this.editForm.parentId!=null"
                        label="父级类型"
                        prop="parentId">
            <el-select v-model="editForm.parentId"
                       placeholder="请选择父级">
              <el-option v-for="item in this.nameList"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注"
                        prop="memo">
            <el-input type="textarea"
                      v-model="editForm.memo"></el-input>
          </el-form-item>

        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="editRecordInfo">确 定</el-button>
        </span>
      </el-dialog>

    </div>
  </div>
</template>
<script>
import {
  getList,
  add,
  deleteSelected,
  deleteCurrent,
  getEditInfo,
  edit,
  getDetail,
  modifySwitch,
} from "@/api/logistics/logisticsGreen.js";
export default {
  data () {
    return {
      // 表格列筛选数据
      tableFilterData: {
        dataList: [

        ],
        dataNow: [
          { label: "	序号	", attr: "id", checked: false },
          { label: "	类型名称	", attr: "name", checked: true },
          { label: "	二级类型名称	", attr: "childrenName", checked: true },
          { label: "	小区id（公共为0）	", attr: "communityId", checked: false },
          { label: "	添加人	", attr: "addUserId", checked: false },
          { label: "	添加人姓名	", attr: "addUserName", checked: true },
          { label: "	添加时间	", attr: "addTime", checked: true },
          { label: "	备注	", attr: "memo", checked: false },

        ],

        checkLabels: [], // 筛选列显示多选框数据
        checkBoxList: [], // 筛选列数据
        indexTwo: 0,
      },
      // 记录列表分页区的参数
      queryInfo: {
        //搜索条件
        query: "",
        // 当前页码
        pagenum: 1,
        //每页显示条数
        pagesize: 7,
      },
      total: 24,


      // 控制添加记录对话框的显示与隐藏
      addDialogVisible: false,
      // 添加记录的表单数据
      addForm: {
        id: "",
        name: "",
        childrenName: "",
        communityId: "",
        addUserId: "",
        addTime: "",
        memo: "",

      },
      // 添加表单校验规则
      addFormRules: {},


      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 查询到的用户信息
      editForm: {},
      // 编辑表单校验规则
      editFormRules: {},


      // 控制详细信息抽屉的显示与隐藏
      drawerVisible: false,
      // 详细信息的表单数据
      detailForm: {},
      // 被选中的记录id
      selectedList: [],
      // 一级类型列表
      nameList: [],

    }
  },
  created () {
    this.getTableList();
  },
  methods: {
    // 获取列表信息
    async getTableList () {
      const { data: res } = await this.$http.get("EquipmenttypeAction/getDetailInfos", { params: this.queryInfo })
      console.log(res)
      if (!res.success) return this.$message.error('获取设备类型数据失败')
      this.tableFilterData.dataList = res.rows
      this.total = res.total


    },

    // 监听多选框选中的所有记录
    handleSelectionChange (val) {
      this.selectedList = val;
    },
    // 监听pagesize改变的事件
    handleSizeChange (newSize) {
      console.log(newSize)
      this.queryinfo.pagesize = newSize
      this.getTableList()
    },
    // 监听页码值改变的事件
    handleCurrentChange (newPage) {
      console.log(newPage)
      this.queryinfo.pagenum = newPage
      this.getTableList()
    },
    // 监听添加对话框的关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 监听修改对话框的关闭
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 表头列筛选功能
    filterFunHandle (type, currentItem, index) {
      if (type === 'filter') { // 筛选列
        if (event.target.checked === false) {
          this.tableFilterData.dataNow.forEach((item, index, arr) => {
            if (item.attr === currentItem) {
              return item.checked = false
            }
          })
        } else {
          this.tableFilterData.dataNow.forEach((item, index, arr) => {
            if (item.attr === currentItem) {
              return item.checked = true
            }
          })
        }
      } else if (type === 'allchecked') { // 全选
        if (this.tableFilterData.checkLabels.length === 0) {
          this.tableFilterData.dataNow.forEach((result) => {
            this.tableFilterData.checkLabels.push(result.attr)
          })
          this.tableFilterData.checkBoxList = this.tableFilterData.checkLabels // 复选框置为复选所有值，全部选择    
        } else {
          this.tableFilterData.checkBoxList = this.tableFilterData.checkLabels // 复选框置为复选所有值，全部选择
        }
        this.tableFilterData.dataNow.forEach((item, index, arr) => {
          item.checked = true
        })
      } else if (type === 'cancel') { // 取消全选
        this.tableFilterData.checkBoxList = [] // 复选框置为空，全部不选择
        this.tableFilterData.dataNow.forEach((item, index, arr) => {
          item.checked = false
        })
      }
    },




    //点击添加类型按钮
    async addType () {
      this.addDialogVisible = !this.addDialogVisible
      const { data: res0 } = await this.$http.get("EquipmenttypeAction/getBasicInfos")
      if (!res0.success) return this.$message.error('获取设备类型数据失败')
      this.nameList = res0.rows
      console.log(this.nameList)

    },

    // 确认添加类型
    addRecord () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        console.log(this.addForm)
        //父级分类非空，则添加类型为二级类型
        if (this.addForm.parentId != null) {
          const { data: res } = await this.$http.post("EquipmenttypechildrenAction/addObject", this.addForm)
          if (!res.success) return this.$message.error('添加设备二级类型失败')
          this.$message.success('添加二级设备类型成功！')
          // 隐藏添加记录的对话框
          this.addDialogVisible = false
          // 重新获取记录列表数据
          this.getTableList()

        } else {   //否则添加类型为一级类型
          const { data: res } = await this.$http.post("EquipmenttypeAction/addObject", this.addForm)
          if (!res.success) return this.$message.error('添加设备一级类型失败')
          this.$message.success('添加一级设备类型成功！')
          // 隐藏添加记录的对话框
          this.addDialogVisible = false
          // 重新获取记录列表数据
          this.getTableList()
        }

      })
    },

    // 查看修改记录（当前记录）
    async showEditDialog (rowInfo) {
      this.editForm = {}
      this.editDialogVisible = true
      console.log(rowInfo)
      //当前类型无父级:为一级类型
      if (rowInfo.parentId == null) {
        const { data: res } = await this.$http.post("EquipmenttypeAction/getObjectById", { id: rowInfo.id })
        if (!res.success)
          return this.$message.error('获取当前一级类型信息失败')
        this.editForm = res.rows[0]
      } else { //有父级，为二级类型
        const { data: res } = await this.$http.post("EquipmenttypechildrenAction/getObjectById", { id: rowInfo.id })
        if (!res.success)
          return this.$message.error('获取当前二级类型信息失败')
        this.editForm = res.rows[0]
      }

      const { data: res0 } = await this.$http.get("EquipmenttypeAction/getBasicInfos")
      if (!res0.success) return this.$message.error('获取设备类型列表失败')
      this.nameList = res0.rows

    },
    // 确认修改
    editRecordInfo () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        // 发起修改记录信息的数据请求
        console.log(this.editForm)
        //当前类型无父级:为一级类型
        if (this.editForm.parentId == null) {
          const { data: res } = await this.$http.post("EquipmenttypeAction/updateNoNull", this.editForm)
          if (!res.success) return this.$message.error('更新一级类型失败！')
          // 关闭对话框
          this.editDialogVisible = false
          // 刷新数据列表
          this.getTableList()
          // 提示修改成功
          this.$message.success('更新一级类型成功！')
        } else {  //有父级，为二级类型
          const { data: res } = await this.$http.post("EquipmenttypechildrenAction/updateNoNull", this.editForm)
          if (!res.success) return this.$message.error('更新二级类型失败！')
          // 关闭对话框
          this.editDialogVisible = false
          // 刷新数据列表
          this.getTableList()
          // 提示修改成功
          this.$message.success('更新二级类型成功！')
        }

      })
    },
    // 删除（当前记录）
    async deleteRecordById (rowInfo) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm('此操作将永久删除该植物类型, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果用户确认删除，返回值为字符串confirm
      // 如果用户取消删除，返回值未字符串cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      //当前类型无父级:为一级类型
      if (rowInfo.parentId == null) {
        const { data: res } = await this.$http.post("EquipmenttypeAction/deleteByIds", { ids: rowInfo.id })
        if (!res.success)
          return this.$message.error('删除当前一级类型信息失败')
        this.$message.success('删除记录成功！')
        this.getTableList()
      } else { //有父级，为二级类型
        const { data: res } = await this.$http.post("EquipmenttypechildrenAction/deleteByIds", { ids: rowInfo.id })
        if (!res.success)
          return this.$message.error('删除当前二级类型信息失败')
        this.$message.success('删除记录成功！')
        this.getTableList()
      }

    },

    // 修改switch开关状态（当前记录）
    async switchStateChanged (recordinfo) {
      console.log(recordinfo)
      await modifySwitch(recordinfo.id, recordinfo.state).then((res) => {
        if (res.data.code !== 200) {
          recordinfo.state = !recordinfo.state
          return this.$message.error('更新状态失败!')
        }
        this.$message.success('更新状态成功!')
      })

    },

  }

}


</script>
<style scoped>
.el-table {
  font-size: 13px;
}
.el-pagination {
  text-align: left;
  padding-top: 20px;
}
</style>